import {defineStore} from 'pinia';
import {ref} from 'vue'
import {createEnterprise,getEnterprises} from "@/api/modules/enterprise";
import useMessage from "@/plugin/useMessage";
import {getUserId} from "@/plugin/auth";

export const useEnterpriseStore = defineStore('enterprise', () => {
  const enterpriseList = ref<EnterpriseItem[]>([])
  const enterprise = ref<EnterpriseItem>({})
  const limit = ref<number>(0)
  const getEnterpriseList = async () => {
    const data = {user_id:getUserId()}
    let res = await getEnterprises(data)
    if (res.code === 200){
      enterpriseList.value = res.data.data
      limit.value = res.data.limit
    }else {
      useMessage(res.code,res.message)
    }
  }
  const create = async (data:EnterpriseType)=>{
    let res = await createEnterprise(data)
    if(res.code === 200){
      if (typeof EnterpriseList.value === 'object'){
        EnterpriseList.value.push(res.data)

      }
    }
    useMessage(res.code,res.message)
    return res
  }
  const setEnterpriseList = (data: EnterpriseItem[]) => {
    enterpriseList.value = data
    enterprise.value = data.find(item => item.is_default === 1)
  }
  const setCurrentEnterprise = (data: EnterpriseType) => {
    enterprise.value = data
  }
  return {
    enterpriseList,
    enterprise,
    getEnterpriseList,
    create,
    setCurrentEnterprise,
    setEnterpriseList,
    limit
  }
}, {persist: true})